package com.sea.base.ext.utils

import android.os.CountDownTimer
import android.os.SystemClock
import androidx.lifecycle.Lifecycle
import com.sea.base.ext.global.createSecondsCountdownTimer
import com.sea.base.ext.obs.doOnDestroyed

/**
 * 带生命周期的倒计时，按秒倒计时参考[createSecondsCountdownTimer]
 */
class LifecycleCountdownTimer(
    lifecycle: Lifecycle,
    millisInFuture: Long,
    countDownInterval: Long = 1000L,
    private val onTickCallback: LifecycleCountdownTimer.(Long) -> Unit,
    private val onFinishCallback: LifecycleCountdownTimer.() -> Unit,
) {
    private val timer = object : CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            this@LifecycleCountdownTimer.onTickCallback(millisUntilFinished)
        }

        override fun onFinish() {
            this@LifecycleCountdownTimer.onFinishCallback()
        }

    }

    init {
        lifecycle.doOnDestroyed { cancel() }
    }

    private var startRealTime = 0L

    /**
     * 当前和start之间的时间差
     */
    val currentDiffTimeMillis get() = SystemClock.elapsedRealtime() - startRealTime

    fun start() {
        startRealTime = SystemClock.elapsedRealtime()
        timer.start()
    }

    fun cancel() {
        timer.cancel()
    }
}